<template>
  <div>
    <el-form
      :model="userForm"
      :rules="rules"
      ref="userForm"
    >
      <el-form-item prop="username">
        <el-input
          v-model="userForm.username"
          placeholder="请输入手机号或者邮箱"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item prop="credential">
        <div class="g-inline">
          <el-input
            placeholder="请输入验证码"
            v-model="userForm.credential"
            clearable
            @keyup.enter.native="submitForm('userForm')"
          ></el-input>
          <el-button
            type="primary"
            style="margin-left: 5px;"
            :disabled="smscode.disabled"
            @click="submitSmsForm('userForm')"
          >{{smscode.tip}}</el-button>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button
          class="g-form"
          type="primary"
          :loading="loading"
          @click="submitForm('userForm')"
        >
          登录
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {
  MobileRegex,
  EMailRegex
} from '@/utils/regex'
import { smsVerifyCode } from '@/api/notification'
import { mailCodeVerify } from '@/api/auth'
import { mapActions } from 'vuex'
export default {
  name: 'LoginForm',
  data () {
    return {
      loading: false,
      codeLoading: false,
      smscode: {
        tip: '发送验证码',
        time: 60,
        timer: null,
        disabled: false
      },
      userForm: {
        username: '',
        credential: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入手机号或者邮箱', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (!MobileRegex.test(value) && !EMailRegex.test(value)) {
                callback(new Error('手机号或者邮箱格式不正确！'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        credential: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
      }
    }
  },
  computed: {
    smsCodeTip1 () {
      return '发送验证码'
    }
  },
  watch: {
    smsCodeTip1 () {
      this.smscode.tip = this.smsCodeTip1
    }
  },
  methods: {
    ...mapActions({
      login: 'user/login'
    }),
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (MobileRegex.test(this.userForm.username)) {
            this.handleSignIn('verification')
          } else if (EMailRegex.test(this.userForm.username)) {
            this.handleSignIn('email')
          }
        } else {
          return false
        }
      })
    },
    // 发送验证码
    submitSmsForm (formName) {
      this.$refs[formName].validateField('username', (errMsg) => {
        if (errMsg) {
        } else {
          if (MobileRegex.test(this.userForm.username)) {
            this.handleVerifyCode('phone')
          } else if (EMailRegex.test(this.userForm.username)) {
            this.handleVerifyCode('email')
          }
        }
      })
    },
    // 发送验证码
    async handleVerifyCode (type = 'phone') {
      this.codeLoading = true
      let message = '验证码已发送，请查看邮箱'
      let response
      switch (type) {
        case 'phone':
          response = await smsVerifyCode(this.userForm.username)
          message = response.data
          break
        case 'email':
          await mailCodeVerify(this.userForm.username)
          break
        default:
          return
      }
      this.codeLoading = false
      this.$notify({
        message,
        duration: 0
      })
      this.smscode.tip = this.smscode.time + '秒后重试'
      this.smscode.disabled = true
      this.smscode.timer = setInterval(() => {
        this.smscode.time--
        if (this.smscode.time > 0) {
          this.smscode.tip = this.smscode.time + '秒后重试'
        } else {
          clearInterval(this.smscode.timer)
          this.smscode.disabled = false
          this.smscode.time = 60
          this.smscode.tip = '重新发送'
        }
      }, 1000)
    },
    // 登录
    async handleSignIn (type) {
      this.loading = true
      try {
        // 验证码登录
        await this.login({ userInfo: this.userForm, type })
        this.loading = false
        // 跳转目标
        const redirect = this.$route.query.redirect
        if (redirect) {
          this.$router.push({ path: redirect })
        } else {
          this.$router.push({ name: 'Home' })
        }
      } catch {
        this.loading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.forget {
  float: right;
}
</style>
